<?php
namespace app\home\controller;

/*
 *许愿墙
 */

use think\Controller;

class Wall extends Controller
{
    private function random_data($num, $table, $where = [], $field = '*', $order = [], $pk = 'Id')
    //随机获取数据
    {
        $countcus = db($table)
            ->field($pk)
            ->where($where)
            ->select();
        if (count($countcus) == 0) {
            return [];
        }
        $arr = [];
        $flag = 0;
        $countnum = count($countcus);
        if ($countnum < $num) {
            $num = $countnum;
        }
        for ($i = 0; $i < $num; $i++) {
            $randnum = $countcus[mt_rand(0, $countnum - 1)][$pk];
            if ($flag != $randnum) {
                if (!in_array($randnum, $arr)) {
                    $arr[] = $randnum;
                    $flag = $randnum;
                } else {
                    $i--;
                }
            }else{
                $i--;
            }
        }
        $list = db($table)
            ->field($field)
            ->where($pk, 'in', $arr)
            ->order('time','desc')
            ->select();
        return $list;
    }

    public function wall()  //许愿墙页面
    {
        return $this->fetch('');
    }

    public function WallJson()  //许愿墙接口
    {

        $Data=$this->random_data(12,'wall');

        return json($Data);
    }

    public function addWish()   //添加梦想
    {
        $content=input('post.');
        $content['time']=date('Y-m-d H:i:s',time());

        $Sql=db('wall')->insert($content);

        if ($Sql)
        {
            Monitor('发布了心愿');
            return json(['result'=>'success']);
        }
        else
            return json(['result'=>'error']);

    }
}
